package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客户端程序
public class UdpEchoClient {
    private DatagramSocket socket;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverPort = serverPort;
        this.serverIP = serverIP;
        socket = new DatagramSocket();//不用指定客户端的端口号，让用户自己的操作系统自己去安排端口号，避免端口号冲突
    }

    public void start() throws IOException {
        System.out.println("欢迎来到客户端...");
        Scanner scan = new Scanner(System.in);
        while(true) {
            //用户从控制台输入数据
            System.out.println("请输入你要发送的数据：");
            while(!scan.hasNext()) {
                break;
            }
            String request = scan.nextLine();

            //构建请求数据包
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);

            //发送数据包
            socket.send(requestPacket);

            //接收数据包
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);

            //打印响应数据
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println("响应：" + response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}